package com.wh1200.mybatis.xmlless.model

import com.wh1200.mybatis.xmlless.AnnotatedElementDetailInfo
import com.wh1200.mybatis.xmlless.model.base.BaseClassWrapper


/**
 *
 * @author 吴昊
 * @date 2024/1/17 10:52
 * @since v0.0.0
 * @version 1.0
 */
data class ClassInfo(
    val fullName: String,
    val isComplexType: Boolean,
    val realType: ClassInfo?,
    val allSuperClassOrInterfaces: List<String>,
    val isCollection: Boolean,
    val isArray: Boolean
) {

  /** 字段列表 */
  var fields: List<AnnotatedElementDetailInfo> = listOf()

  companion object {
    /** 缓存 */
    private val CACHE = mutableMapOf<String, ClassInfo>()

    fun clearCache() {
      CACHE.clear()
    }

    operator fun get(wrapper: BaseClassWrapper): ClassInfo {
      return if (CACHE.containsKey(wrapper.getClassName())) {
        CACHE[wrapper.getClassName()]!!
      } else {
        val isComplexType = wrapper.isComplex()
        val realType = wrapper.getRealType()
        val classInfo = ClassInfo(
            wrapper.getClassName(),
            isComplexType,
            if (realType.getClassName() != wrapper.getClassName()) {
              get(realType)
            } else {
              null
            },
            wrapper.getAllSuperClassesOrInterfaces(),
            wrapper.isCollection(),
            wrapper.isArray()
        )
        // 防止自引用导致无限循环，必须先放入缓存，再解析字段
        CACHE[wrapper.getClassName()] = classInfo
        classInfo.fields = wrapper.getAllFields()
        classInfo
      }
    }
  }

}
